package com.lagou.edu.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author: jie.zhao
 * @create: 2021/08/01 11:30
 */
@Slf4j
@Component
public class AuthFilter implements GlobalFilter , Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String uri = request.getURI().toString();
        if(uri.contains("/api/user") || uri.contains("/api/code")){
                log.info("用户服务和验证码服务经过访问");
                return chain.filter(exchange);
        }
        List<HttpCookie> respAddCK = request.getCookies().get("respAddCK");
        if(CollectionUtils.isEmpty(respAddCK)){
            log.info("ck不正确");
            String result = "Request not denied";
            DataBuffer dataBuffer = response.bufferFactory().wrap(result.getBytes());
            return response.writeWith(Mono.just(dataBuffer));
        }
        log.info("ck合法");
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {

        return 0;
    }
}
